package com.duoduo.springboot.security.core;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.duoduo.springboot.security.dao.RoleDao;
import com.duoduo.springboot.security.dao.UserDao;
import com.duoduo.springboot.security.model.Role;
import com.duoduo.springboot.security.model.User;

@Component
public class CustomUserDetailsService implements UserDetailsService {
	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;

	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		// SysUser对应数据库中的用户表，是最终存储用户和密码的表，可自定义
		// 本例使用SysUser中的name作为用户名:
		User user = userDao.getByAccount(userName);
		if (user == null) {
			throw new UsernameNotFoundException("UserName " + userName + " not found");
		}

		List<Role> userRoles = roleDao.listRolesByUserId(user.getId());

		// SecurityUser实现UserDetails并将SysUser的name映射为username
		SecurityUser seu = new SecurityUser(user, userRoles);
		return seu;
	}

}
